class UsersController < ApplicationController
  before_filter :set_user,
                :except => [ :new, :create, :index ]
  before_filter :set_profile,
                :only => [ :profile, :edit, :update ]
  before_filter :must_belongs_to_current_user,
                :only => [ :profile, :edit, :update ]
  before_filter :current_user_must_be_admin,
                :only => [ :index, :destroy ]

  def new
    @pagetitle = "Register a New User"
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      session[:user_id] = @user.id
      redirect_to( last_uri, :notice => 'Welcome to join us!.' )
    else
      blank_password_field
      render :action => 'new'
    end
  end

  def show
  end

  def edit
  end

  def update
    if @user.update_attributes(params[:user])
      redirect_to(@user, :notice => 'User was successfully updated.')
    else
      render :action => "edit"
    end
  end

# Management  ==============================
  def index
    @users = User.all
  end

  def destroy
    @user.destroy
    redirect_to(users_url)
  end



private
  def must_belongs_to_current_user
    redirect_to_login 'This is not belongs to you.' unless @current_user == @user
  end

  def blank_password_field
    params[:password] = nil
    params[:password_confirmation] = nil
  end

  def set_user
    @user = User.find(params[:user_id] || params[:id])
  end

  def set_profile
    @profile = @user.profile
  end
end
